package com.lemon.core.tenant.config;

import com.baomidou.mybatisplus.extension.plugins.inner.TenantLineInnerInterceptor;
import com.lemon.core.mybatis.config.MybatisPlusConfiguration;
import com.lemon.core.tenant.core.aop.TenantIgnoreAspect;
import com.lemon.core.tenant.core.db.DefaultTenantIdGenerator;
import com.lemon.core.tenant.core.db.LemonTenantHandler;
import com.lemon.core.tenant.core.db.TenantIdGenerator;
import org.springframework.boot.autoconfigure.AutoConfigureBefore;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

/**
 * 多租户自动配置
 *
 * @author pan
 * @since 2020-07-16
 */
@Configuration(proxyBeanMethods = false)
@ConditionalOnProperty(prefix = TenantProperties.PREFIX, value = "enabled", matchIfMissing = true)
@AutoConfigureBefore(MybatisPlusConfiguration.class)
@EnableConfigurationProperties(TenantProperties.class)
public class TenantAutoConfiguration {

    @Bean
    public TenantIgnoreAspect tenantIgnoreAspect() {
        return new TenantIgnoreAspect();
    }

    /**
     * 自定义租户拦截器
     *
     * @param properties 多租户配置
     * @return {@link TenantLineInnerInterceptor}
     */
    @Bean
    @Primary
    public TenantLineInnerInterceptor tenantLineInnerInterceptor(TenantProperties properties) {
        return new TenantLineInnerInterceptor(new LemonTenantHandler(properties));
    }

    /**
     * 自定义租户id生成器
     *
     * @return {@link TenantIdGenerator}
     */
    @Bean
    @ConditionalOnMissingBean(TenantIdGenerator.class)
    public TenantIdGenerator tenantIdGenerator() {
        return new DefaultTenantIdGenerator();
    }

}
